package com.hcinfos.gsoo.ui;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.MyDingzuoAdapter;
import com.hcinfos.gsoo.adapter.MyOrderAdapter;
import com.hcinfos.gsoo.adapter.MyWaimaiAdapter;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.GdTakeAwayOrder;
import com.hcinfos.gsoo.interfaze.OrderCallback;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.LoginUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * 我的预订
 * 
 * @author john
 * 
 */
public class MyOrderActivity extends Activity implements OnClickListener,
		OrderCallback {

	private ImageView back_iv;
	private ListView listView;
	private MyDingzuoAdapter adapter;

	private ObjectMapper mapper;
	public final int OBTAIN_LIST_SUCCESS = 0x2210;
	public final int OBTAIN_LIST_FAIL = OBTAIN_LIST_SUCCESS + 1;
	public final int CANCEL_ORDER_SUCCESS = OBTAIN_LIST_SUCCESS + 2;
	public final int CANCEL_ORDER_FAIL = OBTAIN_LIST_SUCCESS + 3;
	public final int BACK_MONEY_SUCCESS = OBTAIN_LIST_SUCCESS + 4;
	public final int BACK_MONEY_FAIL = OBTAIN_LIST_SUCCESS + 5;
	public final int CHECK_ORDER_SUCCESS = OBTAIN_LIST_SUCCESS + 6;
	public final int CHECK_ORDER_FAIL = OBTAIN_LIST_SUCCESS + 7;
	public final int LOGIN = OBTAIN_LIST_SUCCESS + 8;

	private ImageView staus_iv;
	private ProgressBar progress;
	private Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_dingzuo);
		dialog = DialogUtil.createProgressDialog(this, "操作提示", "正在处理中...");

		staus_iv = (ImageView) findViewById(R.id.staus_iv);
		progress = (ProgressBar) findViewById(R.id.progress);
		mapper = new ObjectMapper();
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);

		listView = (ListView) findViewById(R.id.listView);

		orderList = new ArrayList<GdTakeAwayOrder>();
		adapter = new MyDingzuoAdapter(this, orderList);
		adapter.setCallback(this);
		listView.setAdapter(adapter);
	}

	@Override
	protected void onResume() {
		obtainOrderList();
		super.onResume();
	}

	private HttpUtils httpUtils;
	private RequestParams params;
	private List<GdTakeAwayOrder> orderList;

	private void obtainOrderList() {
		listView.setVisibility(View.GONE);
		progress.setVisibility(View.VISIBLE);
		orderList.clear();
		httpUtils = UtilHttp.getHttpUtils(MyOrderActivity.this);
		params = new RequestParams();
		params.addBodyParameter("sort", "order_datetime desc");
		params.addBodyParameter("beanProxy.orderType", 2 + "");
		httpUtils.send(HttpRequest.HttpMethod.POST, Urls.W_ORDER_LIST, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						LogUtil.e("wxf", arg0.toString());
						handler.sendEmptyMessage(OBTAIN_LIST_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						LogUtil.d("wxf", "obtainOrderList=" + arg0.result);
						try {
							JSONObject obj = new JSONObject(arg0.result);

							int state = obj.getInt("state");
							if (state == 200) {
								List<GdTakeAwayOrder> list = mapper.readValue(
										obj.getString("rows"),
										new TypeReference<List<GdTakeAwayOrder>>() {
										});
								if (list != null)
									orderList.addAll(list);
								handler.sendEmptyMessage(OBTAIN_LIST_SUCCESS);
							} else if (state == 198) {
								handler.sendEmptyMessage(LOGIN);
							} else {
								handler.sendEmptyMessage(OBTAIN_LIST_FAIL);
							}
						} catch (Exception e) {
							LogUtil.e("wxf",
									"obtainOrderList()=" + e.toString());
							handler.sendEmptyMessage(OBTAIN_LIST_FAIL);
						}
					}

				});
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.back_iv:
			finish();
			break;
		}
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			listView.setVisibility(View.VISIBLE);
			progress.setVisibility(View.GONE);
			dialog.dismiss();
			switch (msg.what) {
			case OBTAIN_LIST_SUCCESS:
				progress.setVisibility(View.GONE);
				adapter.setDataChange(orderList);
				if (orderList.size() == 0) {
					Toast.makeText(MyOrderActivity.this, "暂无预订", 500).show();
					staus_iv.setVisibility(View.VISIBLE);
					return;
				}
				staus_iv.setVisibility(View.GONE);
				break;
			case OBTAIN_LIST_FAIL:
				progress.setVisibility(View.GONE);
				staus_iv.setVisibility(View.VISIBLE);
				break;
			case CANCEL_ORDER_FAIL:
				String errorMsg = "取消失败!";
				if (msg.obj != null)
					errorMsg = msg.obj.toString();
				Toast.makeText(MyOrderActivity.this, errorMsg, 500).show();
				break;
			case CANCEL_ORDER_SUCCESS:
				obtainOrderList();
				break;
			case BACK_MONEY_FAIL:
				String moneyMsg = "退款失败!";
				if (msg.obj != null)
					moneyMsg = msg.obj.toString();
				Toast.makeText(MyOrderActivity.this, moneyMsg, 500).show();
				break;
			case BACK_MONEY_SUCCESS:
				obtainOrderList();
				break;
			case CHECK_ORDER_FAIL:
				String checkMsg = "确认失败!";
				if (msg.obj != null)
					checkMsg = msg.obj.toString();
				Toast.makeText(MyOrderActivity.this, checkMsg, 500).show();
				break;
			case CHECK_ORDER_SUCCESS:
				obtainOrderList();
				break;
			case LOGIN:
				LoginUtil.isLoginSuccess(MyOrderActivity.this, handler);
				break;
			case LoginUtil.LOGIN_SUCCESS:
				obtainOrderList();
				break;
			case LoginUtil.LOGIN_FAIL:
				Toast.makeText(MyOrderActivity.this, "获取失败!", 500).show();
				break;
			}
		};
	};

	private Intent intent;

	public void callback(int command, String orderId) {

		switch (command) {
		case 0:
			// 申请退款
			dialog.show();
			backMoney(orderId);
			break;
		case 1:
			dialog.show();
			cancelOrder(orderId);
			// 取消订单
			break;
		case 2:
			intent = new Intent(this, DingzuoOrderDetailActivity.class);
			intent.putExtra("orderId", orderId);
			startActivity(intent);
			// 支付订单
			break;
		case 3:
			dialog.show();
			checkOrder(orderId);
			break;
		// 确认订单

		}
	}

	/**
	 * 申请退款
	 */
	private void backMoney(String orderId) {
		httpUtils = UtilHttp.getHttpUtils(this);
		params = new RequestParams();
		params.addBodyParameter("orderId", orderId);
		httpUtils.send(HttpRequest.HttpMethod.POST, Urls.W_MONEY_CANCEL,
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						handler.sendEmptyMessage(BACK_MONEY_FAIL);

					}

					@Override
					public void onSuccess(ResponseInfo<String> result) {

						try {
							JSONObject obj = new JSONObject(result.result);
							int state = obj.getInt("state");
							String message = obj.getString("message");
							if (state == 200) {
								handler.sendEmptyMessage(BACK_MONEY_SUCCESS);
							} else {
								Message msg = handler.obtainMessage();
								msg.obj = message;
								msg.what = BACK_MONEY_FAIL;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(BACK_MONEY_FAIL);
						}

					}

				});
	}

	/**
	 * 取消订单
	 */
	private void cancelOrder(String orderId) {
		httpUtils = UtilHttp.getHttpUtils(this);
		params = new RequestParams();
		params.addBodyParameter("orderId", orderId);
		httpUtils.send(HttpRequest.HttpMethod.POST, Urls.W_ORDER_CANCEL,
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						handler.sendEmptyMessage(CANCEL_ORDER_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> result) {

						try {
							JSONObject obj = new JSONObject(result.result);
							int state = obj.getInt("state");
							String message = obj.getString("message");
							if (state == 200) {
								handler.sendEmptyMessage(CANCEL_ORDER_SUCCESS);
							} else {
								Message msg = handler.obtainMessage();
								msg.obj = message;
								msg.what = CANCEL_ORDER_FAIL;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(CANCEL_ORDER_FAIL);
						}
					}

				});
	}

	/**
	 * 确认订单
	 * 
	 */
	private void checkOrder(String orderId) {
		httpUtils = UtilHttp.getHttpUtils(this);
		params = new RequestParams();
		params.addBodyParameter("orderId", orderId);
		params.addBodyParameter("token", "");
		params.addBodyParameter("timestamp", "");
		params.addBodyParameter("key", "");
		httpUtils.send(HttpRequest.HttpMethod.POST, Urls.W_CHECK_ORDER, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						LogUtil.e("wxf", arg0.toString());
						handler.sendEmptyMessage(CHECK_ORDER_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {

						String result = arg0.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String errorMsg = obj.getString("message");
							if (state == 200) {
								handler.sendEmptyMessage(CHECK_ORDER_SUCCESS);
							} else {
								Message msg = handler.obtainMessage();
								msg.obj = errorMsg;
								msg.what = CHECK_ORDER_FAIL;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(CHECK_ORDER_FAIL);
							LogUtil.e("wxf", e.toString());
						}
					}
				});
	}
}
